package com.cxb;

import java.io.File;
import java.lang.reflect.Method;

import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.os.PowerManager;
import android.os.RemoteException;
import android.os.StatFs;
import android.provider.Settings;
import android.provider.Settings.SettingNotFoundException;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;

import com.amitek.aidl.mqtt.MqttServiceProxy;
import com.cxb.manager.PowerOffState;
import com.cxb.manager.RootContext;
import com.cxb.receiver.PowerStateReceiver;
import com.cxb.service.CXBMainService;
import com.cxb.utils.CommonUtils;
import com.cxb.utils.Constants;
import com.cxb.utils.Debug;
import com.cxb.utils.SharedPreferencesUtils;
import com.cxb.utils.Tts;

public final class GuardActivity extends BaseActivity {

	private static Dialog sConfirmDialog = null;
	// private static AlertDialog powerOffingDialog = null;
	private static TextView timeView = null;
	private static TextView weixinTipTv = null;
	private static Button btnCancel;
	private static final int MAX_SHUTDOWN_TIME = 9;
	private static final int UPDATETIMEER = 1126;
	private static int shutdown_time = 0;
	private static Handler mTimeHandler = null;
	private static SharedPreferencesUtils spUtils = null;
	private static CheckBox guardCheck = null;
	private ImageView ivPoweroff;
	private AudioManager mAudioManager;
	private ImageView ivShutdownCircle;
	private static int[] poweroff_images = new int[] { R.drawable.countdown_00,
			R.drawable.countdown_01, R.drawable.countdown_02,
			R.drawable.countdown_03, R.drawable.countdown_04,
			R.drawable.countdown_05, R.drawable.countdown_06,
			R.drawable.countdown_07, R.drawable.countdown_08,
			R.drawable.countdown_09 };

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		Debug.printfLog("GuardActivity onCreate");
		spUtils = new SharedPreferencesUtils(this);

		// if (CommonUtils.getVersionType() == CommonUtils.VERSION_ZHAOSHAN) {

		final CloseDialogReceiver closer = new CloseDialogReceiver(this);
		if (sConfirmDialog != null) {
			try {
				sConfirmDialog.dismiss();
				PowerOffState.isPowerOffing = false;
				PowerOffState.setPowerOffing(false);
			} catch (Exception e) {
				Debug.printf(e.toString(), null);
			}
			sConfirmDialog = null;
		}
		if (sConfirmDialog == null) {
			sConfirmDialog = new Dialog(this.getApplicationContext(),
					R.style.full_screen_dialog);
			sConfirmDialog.setContentView(R.layout.poweroff_dialog);
			sConfirmDialog.getWindow().setType(
					WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
			ivPoweroff = (ImageView) sConfirmDialog
					.findViewById(R.id.iv_poweroff);
			btnCancel = (Button) sConfirmDialog.findViewById(R.id.btn_cancel);
			ivShutdownCircle = (ImageView) sConfirmDialog
					.findViewById(R.id.iv_poweroff_circle2);
			ivPoweroff.setImageResource(poweroff_images[MAX_SHUTDOWN_TIME]);
			ivShutdownCircle.startAnimation(AnimationUtils.loadAnimation(this,
					R.anim.shutdown_circle_animation));
			// timeView = new TextView(this);
			// timeView.setGravity(Gravity.CENTER);
			// timeView.setTextSize(45);
			shutdown_time = MAX_SHUTDOWN_TIME;
			btnCancel.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					if (sConfirmDialog != null)
						sConfirmDialog.dismiss();
					sConfirmDialog = null;
					finish();
					// sendBroadcast(new
					// Intent("action_poweroff_dialog_cancel"));
					Intent intent = new Intent();
					intent.setClassName("com.cxb.carrecorder",
							"com.cxb.carrecorder.PreviewService");
					intent.setAction("ACTION_CANCEL_UPLOAD_IMAGE");
					startService(intent);

				}
			});
			mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

			sConfirmDialog.setCancelable(false);// blocking back key
			Debug.printfLog("sConfirmDialog show");
			// ///////////////// add by llx 2013.11.26 ///////////////////////
			mTimeHandler = new Handler(new Callback() {
				@Override
				public boolean handleMessage(Message msg) {
					if (msg.what == UPDATETIMEER) {
						if (sConfirmDialog != null) {
							if (PowerStateReceiver.IsPowerConnected()
									&& !PowerOffState.isPowerOffing) {
								sConfirmDialog.dismiss();
								sConfirmDialog = null;
								finish();
								Log.i("test",
										"upload image action_poweroff_dialog_cancel");
								// sendBroadcast(new Intent(
								// "action_poweroff_dialog_cancel"));

								Intent intent = new Intent();
								intent.setClassName("com.cxb.carrecorder",
										"com.cxb.carrecorder.PreviewService");
								intent.setAction("ACTION_CANCEL_UPLOAD_IMAGE");
								startService(intent);
							} else {
								Debug.printfLog("shutdown_time "
										+ shutdown_time);
								if (shutdown_time > 0) {
									// timeView.setText(String
									// .valueOf(shutdown_time));
									if (shutdown_time < MAX_SHUTDOWN_TIME) {
										ivPoweroff
												.setImageResource(poweroff_images[shutdown_time]);
									}
									if (shutdown_time == MAX_SHUTDOWN_TIME - 3) {

										Debug.printfLog("send shutdown image when 7");
										Intent intent = new Intent();
										intent.setClassName(
												"com.cxb.carrecorder",
												"com.cxb.carrecorder.PreviewService");
										intent.setAction("ACTION_START_UPLOAD_IMAGE");

										startService(intent);
									}
								} else {
									ivPoweroff
											.setImageResource(poweroff_images[0]);
									btnCancel.setVisibility(View.GONE);
									shutdown();
									// sConfirmDialog.dismiss();
									sConfirmDialog = null;
									// finish();
								}
							}
						}
					}
					return false;
				}
			});

			// 应用程序的关系对话框显示不到行车记录仪前面,所以要把行车记录仪隐藏才能看到关机对话框
			Intent iRecorder = new Intent();
			iRecorder.setAction("preview_window_off");
			sendBroadcast(iRecorder);

			new Thread(new Runnable() {
				@Override
				public void run() {
					while (sConfirmDialog != null) {
						try {
							Thread.sleep(1000);
						} catch (Exception e) {
							e.printStackTrace();
						}

						shutdown_time--;
						Message msg = mTimeHandler.obtainMessage();
						msg.what = UPDATETIMEER;
						mTimeHandler.sendMessage(msg);

						if (shutdown_time < 0)
							break;
					}
				}
			}).start();
			// ///////////////////////////////////////////////////////////////
		}

		checkSpaceNclean();
		closer.dialog = sConfirmDialog;
		sConfirmDialog.setOnDismissListener(closer);

		if (!sConfirmDialog.isShowing()) {

			sConfirmDialog.show();
		}

		// //////////////上传图片///////////////////
		if (!CommonUtils.isNetworkAvailable(this)) {
			Tts.showToast(this,
					getString(R.string.network_error_upload_image_maybe_fail),
					0);
		}
		// if (!CommonUtils.isServiceRunning(this,
		// "com.cxb.carrecorder.PreviewService")) {
		// Intent recorderIntent = new Intent();
		// recorderIntent.setClassName("com.cxb.carrecorder",
		// "com.cxb.carrecorder.PreviewService");
		// startService(recorderIntent);
		// }

		PowerOffState.power_off_time = System.currentTimeMillis();

		super.onCreate(savedInstanceState);
	}

	private static class CloseDialogReceiver extends BroadcastReceiver
			implements DialogInterface.OnDismissListener {
		private Context mContext;
		public Dialog dialog;

		CloseDialogReceiver(Context context) {
			mContext = context;
			IntentFilter filter = new IntentFilter(
					Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
			try {

				context.registerReceiver(this, filter);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		@Override
		public void onReceive(Context context, Intent intent) {
			dialog.cancel();
		}

		public void onDismiss(DialogInterface unused) {
			try {
				mContext.unregisterReceiver(this);

			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	private long getFreespace() {
		File path = new File("/mnt/sdcard/");
		StatFs statfs = new StatFs(path.getPath());
		long blocSize = statfs.getBlockSize();
		long availaBlock = statfs.getAvailableBlocks();
		return blocSize * availaBlock;
	}

	private final String[] filesaves = { "autonavidata70", "Android" };

	private void checkSpaceNclean() {
		if (getFreespace() < 1024 * 1024) {
			File fliesdcard = new File("/mnt/sdcard/");
			File[] files = fliesdcard.listFiles();
			boolean hasfile;
			for (int i = 0; files != null && i < files.length; i++) {
				hasfile = false;
				for (String name : filesaves)
					if (name.equals(files[i].getName())) {
						hasfile = true;
						break;
					}

				if (!hasfile)
					files[i].delete();
			}
		}
	}

	public static void dismissDialog() {
	}

	private void shutdown() {

		PowerOffState.isPowerOffing = true;
		PowerOffState.setPowerOffing(true);
		Debug.printfLog("shutdown-->actionShutDown...");

		new Thread() {
			public void run() {
				MqttServiceProxy mqttProxy = CXBMainService.getMqttProxy();
				if (mqttProxy != null) {
					try {
						mqttProxy.sendTrackStop(true);
					} catch (RemoteException e) {
						e.printStackTrace();
					}// 行程结束
				}
			};
		}.start();
		RootContext.getInstance().runCommand("setprop service.bootanim.exit 0");
		RootContext.getInstance().runCommand(
				"setprop  ctl.start 'bootanim:shut nomp3'");

		try {
			spUtils.setBrightness(Settings.System.getInt(getContentResolver(),
					Settings.System.SCREEN_BRIGHTNESS));
		} catch (SettingNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		final int preVolumn = mAudioManager
				.getStreamVolume(AudioManager.STREAM_MUSIC);
		mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 0, 0);
		mAudioManager.setStreamVolume(AudioManager.STREAM_NOTIFICATION, 0, 0);
		mAudioManager.setStreamVolume(AudioManager.STREAM_SYSTEM, 0, 0);
		mAudioManager.setStreamVolume(AudioManager.STREAM_RING, 0, 0);
		mAudioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);

		spUtils.setLastVoulmn(preVolumn);
		PowerOffState.isPowerOffing = true;
		PowerOffState.setPowerOffing(true);
		Intent poweroffIntent = new Intent(Constants.ACTION_POWER_OFFING);

		sendBroadcast(poweroffIntent);

		//终止云知声
		RootContext
		.runCommandForResult("am force-stop com.chemi.framework");
        RootContext
		.runCommandForResult("am force-stop com.unisound.unicar.gui");

		mTimeHandler.postDelayed(new Runnable() {

			@Override
			public void run() {
				poweroff();
			}
		}, 36000);
		new Handler().postDelayed(new Runnable() {

			@Override
			public void run() {
				try {

					PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
					Method method = powerManager.getClass().getMethod(
							"setBacklightOffForWfd", boolean.class);
					method.invoke(powerManager, true);
//					// 记录最后的亮度
//					Settings.System.putInt(getContentResolver(),
//							Settings.System.SCREEN_BRIGHTNESS, 0);

				} catch (Exception e1) {

					e1.printStackTrace();
				}

			}
		}, 5000);

	}

	private void poweroff() {
		Debug.printfLog("poweroff...");
		RootContext.getInstance().runCommand("reboot -p");

	}
}
